<template>
  <!-- 系统目录 西成药品 -->
  <div class="MedicenCata">
    <!-- main -->
    <div class="main">
      <!-- right -->
      <div class="main-right">
        <!-- tit -->
        <div class="main-icon">
          <div class="main-icon-a">
            <i :class="iconComes"
               style="border-radius: 50%;font-size: 20px;padding: 6px;margin-left: 8px;;background-color: #5a5a5a;color: #fff;"></i>
            <span style="font-size: 12px;font-weight:bold;margin-left: 12px;color: #606266;">{{ CatalogueName }}</span>
          </div>
          <!-- btn1 -->
          <div class="main-icon-b">
            <span style="font-size: 12px;color: #606266;font-weight: bold;">状态：</span>
            <el-dropdown @command="handleCommand" trigger="click">
              <span class="el-dropdown-link">{{ DropDownedName }}<i class="el-icon-down"></i></span>
              <el-dropdown-menu slot="dropdown">
                <el-dropdown-item command="a">可用</el-dropdown-item>
                <el-dropdown-item command="b">禁用</el-dropdown-item>
                <el-dropdown-item command="c" divided>全部</el-dropdown-item>
              </el-dropdown-menu>
            </el-dropdown>
          </div>
          <!-- 按钮栏 -->
          <div class="main-icon-c">
            <span
                style="font-size: 12px;color: #606266;font-weight: bold;display: inline-block;width: 68px;">关键字：</span>
            <el-input size="mini" placeholder="输入名称进行搜索" v-model="searchValue"  @keyup.enter.native="handClick(0)"></el-input>
          </div>
          <!-- 按钮栏 -->
          <div class="main-icon-c">
            <el-button v-for="(v,i) in headerBtn" :key="i" :type="v.type" :loading="loading" :icon="v.icon" size="mini"
                       v-if="!v.auth || permissionsArr.includes(v.auth)"
                       @click="handClick(i)">{{ v.title }}
            </el-button>
          </div>
        </div>
        <!-- add data -->
        <!-- table -->
        <div class="table">
          <el-table :data="tableData" border @row-dblclick="handledbRow">
            <el-table-column v-for="(col, inx) in tableRows" :key="inx" :type="col.type"
                             :prop="col.prop" :label="col.name" :render-header="labelHead" align="center"
                             :min-width="getColumnWidth(col.label,col.prop,tableData)">

              <template #default="{ row }">
                {{ safeGetMappedValue(col, row) }}
              </template>
            </el-table-column>
            <!-- fixed -->

            <el-table-column fixed="left" label="行号" type="index"></el-table-column>
            <!-- edit -->
            <el-table-column fixed="right" label="操作" width='158' v-if="permissionsArr.includes('system:registertype:edit')">
              <template slot-scope="scope">
                <div class="editbox" style="text-align: center;">
                  <el-button type="primary" @click="handleClickEdit(scope.row)" size="mini" >编辑</el-button>
                  <el-button :type="scope.row.status === '1' ? 'danger' : 'success'"
                             @click="handleStartOrDisabled(scope.row)" size="mini">
                    {{ scope.row.status === '1' ? '禁用' : '启用' }}
                  </el-button>
                </div>
              </template>
            </el-table-column>
          </el-table>
        </div>
        <!-- 分页 -->
        <el-pagination
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
            :current-page="pageNum"
            :page-sizes="[8, 16, 24]"
            :page-size="pageSize"
            :total="totalSize"
            layout="total, sizes, prev, pager, next, jumper"
            background>
        </el-pagination>
      </div>
    </div>


    <!-- 新增挂号类别表单 -->
    <div class="feet">
      <div class="addmessagesBox">
        <el-dialog title="新增挂号类别" :visible.sync="addDialogVisible" width="50%" :before-close="handleClose"
                   :close-on-click-modal="false" class="compact-form">
          <!-- tabs -->
          <div class="tabs">
            <div class="tabsMain">
              <!-- tabs-left -->
              <div class="tabs-left">
                <!-- 表单 -->
                <el-form :model="addForm" label-width="85px" size="mini" :rules="formRules" ref="addFormRef">
                  <el-row :gutter="20">
                    <el-col :span="v.spanRows" type="flex" v-for="(v,i) in addcategory" :key="i">
                      <!-- input -->
                      <el-form-item v-if="v.type == 'input'" :prop="v.modelValue" :rules="getFieldRules(v)"
                                    :label="v.label"
                                    :style="v.modelValue === 'designation' ? { marginLeft: '-27px' } : {}">
                        <el-input :suffix-icon='v.prefix' v-model="$data.addForm[v.modelValue]"
                                  @input="addInputMonitor(v,i)" :disabled="v.disabled"
                                  placeholder="请输入内容"></el-input>
                      </el-form-item>
                      <!-- input -->
                      <el-form-item v-if="v.type == 'textarea'" :prop="v.modelValue" :rules="getFieldRules(v)"
                                    :label="v.label">
                        <el-input :type="v.type" :suffix-icon='v.prefix' v-model="$data.addForm[v.modelValue]"
                                  placeholder="请输入内容" :disabled="v.disabled"></el-input>
                      </el-form-item>
                      <!-- select -->
                      <el-form-item v-if="v.type == 'select'" :prop="v.modelValue" :rules="getFieldRules(v)"
                                    :label="v.label">
                        <el-select v-model="$data.addForm[v.modelValue]" filterable placeholder="请选择"
                                   @focus="addEvent(v,i)" @change="addEventChangge">
                          <el-option v-for="item in $data[v.op]" :key="item.id" :label="item.label" :value="item.id">
                            <span style="float: center; color: #8492a6; font-size: 12px">{{ item.label }}</span>
                          </el-option>
                        </el-select>
                      </el-form-item>
                      <!-- timePicker -->
                      <el-form-item v-if="v.type == 'timePicker'" :prop="v.modelValue" :rules="getFieldRules(v)"
                                    :label="v.label" class="compact-time-pickers">
                        <el-time-picker v-model="timeRange" is-range range-separator="-" start-placeholder="开始时间"
                                        end-placeholder="结束时间" format="HH:mm:ss" value-format="HH:mm:ss" size="mini"
                                        :picker-options="{selectableRange: '00:00:00 - 23:59:59'}"
                                        @change="handleTimeRangeChange" class="super-mini-time-picker">>
                        </el-time-picker>
                      </el-form-item>
                      <!-- input Number -->
                      <el-form-item v-if="v.type == 'inputNumber'" :prop="v.modelValue" :rules="getFieldRules(v)"
                                    :label="v.label">
                        <el-input-number v-model="$data.addForm[v.modelValue]" controls-position="right" :min="v.min"
                                         :max="200"></el-input-number>
                      </el-form-item>
                    </el-col>
                  </el-row>
                  <template>
                    <div class="multi-select-container">
                      <div class="select-row">
                        <span class="select-label" style="margin-left: -10px">职称设置:</span>
                        <div class="select-with-tags">
                          <el-select
                              v-model="selectedValues"
                              multiple
                              filterable
                              placeholder="请选择职称"
                              @focus="handleSelectionChange"
                              size="mini"
                          >
                            <el-option
                                v-for="item in profttlIds"
                                :key="item.id"
                                :label="item.label"
                                :value="item.id"
                            >
                            </el-option>
                          </el-select>

                          <div class="selected-tags" v-if="selectedValues.length > 0">
                            <el-tag
                                v-for="(value, index) in selectedValues"
                                :key="index"
                                closable
                                @close="removeItem(index)"
                                type="info"
                                size="mini"
                            >
                              {{ getLabelById(value) }}
                            </el-tag>
                          </div>
                        </div>
                      </div>
                    </div>
                  </template>

                  <div class="table-header">
                    <span>对应费用:</span>
                    <el-button-group class="transparent-btn-group">
                      <el-button icon="el-icon-plus" size="mini" class="transparent-btn"
                                 @click="addPriceDialogVisible = true"></el-button>
                      <el-button icon="el-icon-edit" size="mini" class="transparent-btn" :disabled="!selectedRow"
                                 @click="handlePriceEdit"></el-button>
                      <el-button icon="el-icon-circle-close" size="mini" class="transparent-btn" :disabled="!selectedRow"
                                 @click="handlePriceDelete"></el-button>
                    </el-button-group>
                  </div>
                  <el-table :data="tableData2" border
                            @row-click="handleRowClick"
                            highlight-current-row
                            ref="myTable">
                    <template v-for="col in tableRows2">
                      <el-table-column
                          :key="col.prop"
                          :type="col.type"
                          :prop="col.prop"
                          :label="col.name"
                          :formatter="(row) => formatColumn(row, col.prop)"
                          align="center"
                      ></el-table-column>
                    </template>
                    <!-- fixed -->
                    <el-table-column fixed="left" label="行号" type="index" width="50"></el-table-column>
                  </el-table>
                </el-form>
                合计: {{
                  tableData2.reduce((sum, item) => {
                    return sum + (Number(item.num) || 0) * (Number(item.odcost) || 0);
                  }, 0)
                }}元
              </div>

            </div>
          </div>
          <div slot="footer" class="dialog-footer">
            <el-button size="mini" type="primary" @click="addCategoryData">确定</el-button>
            <el-button size="mini" @click="handleClose">取消</el-button>
          </div>
        </el-dialog>


      </div>

      <!-- messagesBox -->
      <div class="messagesBox">


      </div>
    </div>

    <!-- 修改挂号类别表单 -->
    <div class="feet">
      <div class="editmessagesBox">
        <el-dialog :title="dynamicTitle" :visible.sync="editDialogVisible" width="50%" :before-close="handleClose"
                   :close-on-click-modal="false" class="compact-form">
          <!-- tabs -->
          <div class="tabs">
            <div class="tabsMain">
              <!-- tabs-left -->
              <div class="tabs-left">
                <!-- 表单 -->
                <el-form :model="editForm" label-width="85px" size="mini" :rules="formRules" ref="addFormRef"
                         :disabled="isLookData">
                  <el-row :gutter="20">
                    <el-col :span="v.spanRows" type="flex" v-for="(v,i) in addcategory" :key="i">
                      <!-- input -->
                      <el-form-item v-if="v.type == 'input'" :prop="v.modelValue" :rules="getFieldRules(v)"
                                    :label="v.label"
                                    :style="v.modelValue === 'designation' ? { marginLeft: '-27px' } : {}">
                        <el-input :suffix-icon='v.prefix' v-model="$data.editForm[v.modelValue]"
                                  @input="addInputMonitor(v,i)" :disabled="v.disabled"
                                  placeholder="请输入内容"></el-input>
                      </el-form-item>
                      <!-- input -->
                      <el-form-item v-if="v.type == 'textarea'" :prop="v.modelValue" :rules="getFieldRules(v)"
                                    :label="v.label">
                        <el-input :type="v.type" :suffix-icon='v.prefix' v-model="$data.editForm[v.modelValue]"
                                  placeholder="请输入内容" :disabled="v.disabled"></el-input>
                      </el-form-item>
                      <!-- select -->
                      <el-form-item v-if="v.type == 'select'" :prop="v.modelValue" :rules="getFieldRules(v)"
                                    :label="v.label">
                        <el-select v-model="$data.editForm[v.modelValue]" filterable placeholder="请选择"
                                   @focus="addEvent(v,i)" @change="addEventChangge">
                          <el-option v-for="item in $data[v.op]" :key="item.id" :label="item.label" :value="item.id">
                            <span style="float: center; color: #8492a6; font-size: 12px">{{ item.label }}</span>
                          </el-option>
                        </el-select>
                      </el-form-item>
                      <!-- timePicker -->
                      <el-form-item v-if="v.type == 'timePicker'" :prop="v.modelValue" :rules="getFieldRules(v)"
                                    :label="v.label" class="compact-time-pickers">
                        <el-time-picker v-model="timeRange" is-range range-separator="-" start-placeholder="开始时间"
                                        end-placeholder="结束时间" format="HH:mm:ss" value-format="HH:mm:ss" size="mini"
                                        :picker-options="{selectableRange: '00:00:00 - 23:59:59'}"
                                        @change="handleTimeRangeChange2" class="super-mini-time-picker">>
                        </el-time-picker>
                      </el-form-item>
                      <!-- input Number -->
                      <el-form-item v-if="v.type == 'inputNumber'" :prop="v.modelValue" :rules="getFieldRules(v)"
                                    :label="v.label">
                        <el-input-number v-model="$data.editForm[v.modelValue]" controls-position="right" :min="v.min"
                                         :max="200"></el-input-number>
                      </el-form-item>
                    </el-col>
                  </el-row>
                  <template>
                    <div class="multi-select-container">
                      <div class="select-row">
                        <span class="select-label" style="margin-left: -10px">职称设置:</span>
                        <div class="select-with-tags">
                          <el-select
                              v-model="selectedValues"
                              multiple
                              filterable
                              placeholder="请选择职称"
                              @focus="handleSelectionChange"
                              size="mini"
                          >
                            <el-option
                                v-for="item in profttlIds"
                                :key="item.id"
                                :label="item.label"
                                :value="item.id"
                            >
                            </el-option>
                          </el-select>

                          <div class="selected-tags" v-if="selectedValues.length > 0">
                            <el-tag
                                v-for="(value, index) in selectedValues"
                                :key="index"
                                closable
                                @close="removeItem(index)"
                                type="info"
                                size="mini"
                            >
                              {{ getLabelById(value) }}
                            </el-tag>
                          </div>
                        </div>
                      </div>
                    </div>
                  </template>

                  <div class="table-header">
                    <span>对应费用:</span>
                    <el-button-group class="transparent-btn-group">
                      <el-button type="" icon="el-icon-plus" size="mini" class="transparent-btn"
                                 @click="addPriceDialogVisible = true"></el-button>
                      <el-button type="" icon="el-icon-edit" size="mini" class="transparent-btn"
                                 :disabled="!selectedRow" @click="handlePriceEdit"></el-button>
                      <el-button type="" icon="el-icon-circle-close" size="mini" class="transparent-btn"
                                 :disabled="!selectedRow" @click="handlePriceDelete"></el-button>
                    </el-button-group>
                  </div>
                  <el-table :data="tableData2" border
                            @row-click="handleRowClick"
                            highlight-current-row
                            :style="{ width: windowWidth + 'px' }"
                            ref="myTable">
                    <template v-for="col in tableRows2">
                      <el-table-column
                          :key="col.prop"
                          :type="col.type"
                          :prop="col.prop"
                          :label="col.name"
                          :formatter="(row) => formatColumn(row, col.prop)"
                          align="center"
                      ></el-table-column>
                    </template>
                    <!-- fixed -->
                    <el-table-column fixed="left" label="行号" type="index" width="50"></el-table-column>
                  </el-table>
                </el-form>
                合计: {{
                  tableData2.reduce((sum, item) => {
                    return sum + (Number(item.num) || 0) * (Number(item.odcost) || 0);
                  }, 0)
                }}元
              </div>

            </div>
          </div>
          <div slot="footer" class="dialog-footer">
            <el-button size="mini" type="primary" @click="submitForm" :disabled="isLookData">修改</el-button>
            <el-button size="mini" @click="handleClose">取消</el-button>
          </div>
        </el-dialog>

      </div>

      <!-- messagesBox -->
      <div class="messagesBox">


      </div>
    </div>

    <div class="tabs">
      <el-dialog
          :close-on-click-modal="false"
          title="对应费用-修改"
          :visible.sync="editPriceDialogVisible"
          width="35%"
          :before-close="handleEditPriceClose">

        <el-form :model="editPriceForm" size="mini" class="compact-form"
                 style="display: flex; flex-direction: column; align-items: center;">
          <el-form-item label="项目名称:" prop="code" style="width: 100%; display: flex; justify-content: center;">
            <el-select
                filterable
                :filter-method="handleSimpleSearch"
                v-model="editPriceForm.costid"
                placeholder="请选择"
                style="width: 180px;" @focus="loadItemPriceOptions">
              <el-option
                  v-for="item in itemPriceOptions"
                  :key="item.id"
                  :label="item.label"
                  :value="item.id"
              ></el-option>
            </el-select>
          </el-form-item>

          <el-form-item label="项目数量:" prop="num" style="width: 100%; display: flex; justify-content: center;">
            <el-input-number
                :min="1"
                :precision="0"
                :controls="false"
                v-model.number="editPriceForm.num"
                @change="handleEditNumChange"
                style="width: 180px;">
            </el-input-number>
          </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
    <el-button type="primary" size="mini" @click="handleEditPriceData">确 定</el-button>
    <el-button size="mini" @click="handleEditPriceClose">取 消</el-button>
  </span>
      </el-dialog>
    </div>

    <div class="tabs">
      <el-dialog
          :close-on-click-modal="false"
          title="对应费用-新增"
          :visible.sync="addPriceDialogVisible"
          width="35%"
          :before-close="handleAddPriceClose">

        <el-form :model="addPriceForm" size="mini" class="compact-form"
                 style="display: flex; flex-direction: column; align-items: center;">
          <el-form-item label="项目名称:" prop="code" style="width: 100%; display: flex; justify-content: center;">
            <el-select
                filterable
                :filter-method="handleSimpleSearch"
                v-model="addPriceForm.costid"
                placeholder="请选择"
                style="width: 180px;" @focus="loadItemPriceOptions">
              <el-option
                  v-for="item in itemPriceOptions"
                  :key="item.id"
                  :label="item.label"
                  :value="item.id"
              ></el-option>
            </el-select>
          </el-form-item>

          <el-form-item label="项目数量:" prop="num" style="width: 100%; display: flex; justify-content: center;">
            <el-input-number
                :min="1"
                :precision="0"
                :controls="false"
                v-model="addPriceForm.num"
                @change="handleNumChange"
                style="width: 180px;">
            </el-input-number>
          </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
    <el-button type="primary" size="mini" @click="handleAddPriceData">确 定</el-button>
    <el-button size="mini" @click="handleAddPriceClose">取 消</el-button>
  </span>
      </el-dialog>
    </div>
  </div>
</template>/

<script>
import
{
  docregistertype,
  getChargingPrice, dict, addCategoryData, getCategory, editCategoryData
}
  from "../../../api/Outpatient/category.js";
import Acccategory from './addcategory.js'
import AccType from "@/views/systemCatalogue/chargingPrice/AddType";
import {pinyin} from "pinyin-pro";
import {updateChargePrice} from "@/api/Outpatient/chargingPrice";
import dayjs from "dayjs";
import {withLoading} from "@/untils/loading";

export default {
  components: {},
  data() {
    return {
      defaultProps: {
        children: 'children',
        label: 'label'
      },
      timeRange: [
        dayjs().startOf('day').format('HH:mm:ss'),
        dayjs().endOf('day').format('HH:mm:ss'),
      ],
      selectedValues: [],
      watch: '查看',
      searchValue: '',
      toCodeNum: '0000',//拼接自增 导零
      CatalogueName: '挂号类别',
      windowWidth: '',
      DropDownedName: '全部',
      typeValue: '',
      YNuseVaule: '可用',
      nowDateTimeValue: '',
      iconComes: 'el-icon-cflx',
      operatingTime: '',
      // str use
      statDateTime: '',
      // boolean
      disabled: true,
      loading: false,
      formdisabled: true,
      dialogVisible: false,	//此乃查看/编辑控制
      addDialogVisible: false,  //此乃新增控制
      editDialogVisible: false,  //此乃新增控制
      addPriceDialogVisible: false,
      editPriceDialogVisible: false,
      selectedRow: null,
      dataIndex: 0,
      CodeNumber: 0,
      topNum: 999, // 上下限
      upNum: 0,
      pageNum: 1, //当前页currentPage
      pageSize: 8,
      totalSize: 10, //总条数
      pageDataState: null,
      addcategory: [],
      itemPriceOptions: [],
      addPriceForm: {
        id: null,
        num: 1,
        odcost: null,
      },
      editPriceForm: {
        id: null,
        num: null,
        odcost: null,
      },
      /* obj */
      // 新增
      addForm: {
        designation: '',
        status: 1,
        pycode: '',
        startTime: dayjs().startOf('day').format('HH:mm:ss'),  // 00:00:00
        endTime: dayjs().endOf('day').format('HH:mm:ss'),    // 23:59:59
        endage: 200,
        startage: 0,
        registertype: null,
        remark: "",
        profttlIds: [],
        regJoinVOS: []
      },
      isLookData: false,
      dynamicTitle: '',
      editForm: {
        id: null,
        designation: '',
        status: 1,
        pycode: '',
        starttime: '',
        endage: null,
        startage: null,
        endtime: '',
        registertype: null,
        remark: "",
        profttlVOS: [],
        costnametableVOS: [],
        profttlIds: [],
        regJoinVOS: []
      },
      formRules: {
        designation: [
          {required: true, message: '名称不能为空', trigger: 'blur'},
        ],
        status: [
          {required: true, message: '请选择有效状态', trigger: 'change'}
        ],
        registertype: [
          {required: true, message: '请选择挂号类型', trigger: 'change'}
        ],
        // 使用时间验证（timeRange需要单独处理）
        timeRange: [
          {
            validator: (rule, value, callback) => {
              if (!value || value.length !== 2) {
                callback(new Error('请选择完整的时间范围'));
              } else {
                callback();
              }
            },
            trigger: 'change'
          }
        ]
      },
      form: {
        classificationCode: "001",
        code: "",
        dosageName: "",
        operationTime: "",
        operator: "",
        pinyinCode: "",
        remark: "",
        systemSerial: "1",
        validStatus: ""
      },

      elTree: [{label: '全部'}],
      userInfo: [],
      watchData: [],
      profttlIds: [],
      statusOptions: [{id: 1, label: '有效'}, {id: 0, label: '禁用'}],
      TypeOption: [{id: 1, label: '普通挂号'}, {id: 2, label: '急诊挂号'}, {id: 3, label: '简易门诊'}, {id: 4, label: '免费挂号'},{id:5,label:'专家挂号'}],
      headerBtn: [
        {search: "search", title: "搜索", type: "success"},
        {add: "add", title: "新增", type: "warning",auth:'system:registertype:add'},
      ],
      tableRows: [
        {name: "系统序号", prop: "id", type: ""}, {name: "名称", prop: "designation", type: ""},
        {name: "挂号类别", prop: "registertype", type: "", op: "TypeOption"}, {
          name: "有效状态",
          prop: "status",
          type: "",
          op: "statusOptions"
        },
        {name: "操作人", prop: "staffName", type: ""}, {name: "合计费用", prop: "odcost", type: ""}, {
          name: "操作时间",
          prop: "operatingTime",
          nz: "nz"
        },
        {name: "开始时间", prop: "starttime", type: ""}, {name: "结束时间", prop: "endtime", type: ""},
        {name: "备注", prop: "remark", type: ""},
      ],
      tableRows2: [
        {name: "项目名称", prop: "costid", type: ""}, {name: "门诊单价", prop: "odcost", type: ""}, {
          name: "数量",
          prop: "num",
          type: ""
        }
      ],
      tableData: [],
      tableData2: [],
      tableData3: [],
      permissionsArr: [],
    };
  },
  computed: {
    // 格式化数字，确保4个0后的数字自增时不会出现前导零
    formattedNumber() {
      return '00000' + this.toCodeNum.toString().slice(1);
    },
  },
  mounted() {
    this.addcategory = Acccategory.map(function (v) {
      return v
    })
    this.dataIndex++
    this.loadData();
    this.permissionsArr = JSON.parse(localStorage.getItem('permissions'))
    this.userInfo = JSON.parse(localStorage.getItem('userInfo'));
    this.addForm.operator = this.userInfo.username
    //获取动态盒子宽度，实时赋值给右侧 => this.$refs.mainRight.offsetWidth;
    this.$nextTick(() => {
      this.updateWindowWidth();
      window.addEventListener('resize', this.updateWindowWidth);
    })
  },
  methods: {
    handleEditNumChange(value) {
      if (value === null || value === undefined || value < 1 || !Number.isInteger(value)) {
        this.$nextTick(() => {
          this.editPriceForm.num = 1; // 强制重置为1
        });
        this.$message.warning('项目数量必须是不小于1的整数');
      }
    },
    handleNumChange(value) {
      // 确保输入为整数且不小于1
      if (isNaN(value) || value < 1 || !Number.isInteger(value)) {
        this.$nextTick(() => {
          this.addPriceForm.num = 1;
        });
        this.$message.warning('项目数量必须是不小于1的整数');
      }
    },
    handleEditPriceClose() {
      this.editPriceForm = Object.assign({}, this.$options.data.call(this).editPriceForm)
      this.editPriceForm.num = 1;
      this.selectedRow = null;
      this.editPriceDialogVisible = false;
    },
    handleAddPriceClose() {
      this.addPriceForm = Object.assign({}, this.$options.data.call(this).addPriceForm)
      this.addPriceForm.num = 1;
      this.selectedRow = null;
      this.addPriceDialogVisible = false;
    },
    /*---------项目名称名字和字母搜索---------*/
    handleSimpleSearch(query) {
      if (!query) {
        this.itemPriceOptions = [...this.itemPriceOptions];
        return;
      }
      const lowerQuery = query.toLowerCase();
      this.itemPriceOptions = this.itemPriceOptions.filter(item => {
        return (
            item.label.includes(query) ||
            (item.pycode && item.pycode.toLowerCase().includes(lowerQuery))
        );
      });
    },

    /*---------表单验证---------*/
    async handleClickEdit(data) {
      this.dynamicTitle = '编辑';
      this.isLookData = false;
      this.selectedRow = null;
      this.tableData2 = [];
      this.selectedValues = [];
      const res = await getCategory({regTyped: data.id})
      await this.handleSelectionChange();
      await this.loadItemPriceOptions();
      this.selectedValues = res.data.profttlVOS.map(item => item.id)
      this.tableData2 = res.data.costnametableVOS
      this.timeRange = [
        dayjs().startOf('day').format('HH:mm:ss'),
        dayjs().endOf('day').format('HH:mm:ss'),
      ];
      this.editForm = {...res.data}
      this.editForm.status = parseInt(this.editForm.status)
      this.editForm.registertype = parseInt(this.editForm.registertype)
      this.editDialogVisible = true;
    },


    /*---------表单验证---------*/
    getFieldRules(field) {
      const requiredFields = ['profttlIds', 'regJoinVOS', 'registertype', 'status'];
      if (requiredFields.includes(field.modelValue)) {
        return [{required: true, message: `${field.label}不能为空`,}];
      }
      return [];
    },

    async submitForm() {
      try {
        // 1. 表单验证
        await this.$refs.addFormRef.validate();
        const action = this.editDialogVisible ? 'edit' : 'add';
        const apiMethod = action === 'edit' ? this.editCategoryData : this.addCategoryData;
        await apiMethod();
        this.$refs.addFormRef.resetFields();
        await this.loadData();
      } catch (error) {
        if (error instanceof Error) {
          this.$message.warning('请检查表单填写是否正确');
        } else {
          this.$message.error('系统异常:请联系管理员');
        }
      }
    },

    /*---------时间处理---------*/
    handleTimeRangeChange(val) {
      this.addForm.starttime = val[0]; // 开始时间
      this.addForm.endtime = val[1];   // 结束时间
    },

    handleTimeRangeChange2(val) {
      this.editForm.starttime = val[0]; // 开始时间
      this.editForm.endtime = val[1];   // 结束时间
    },

    /*---------名称转拼音简码---------*/
    addInputMonitor(v, i) {
      switch (i) {
        case 0:
          this.addForm.pycode =
              pinyin(this.addForm.designation, {pattern: 'first', toneType: 'none', separator: ''}).toLocaleUpperCase();
          break;
      }
    },

    /*---------职称下拉框处理---------*/
    async handleSelectionChange() {
      const res = await dict();
      this.profttlIds = res.data.profttlEntities.filter(v => v.type === 1).map(v => {
        return {label: v.name, id: v.id}
      })
    },

    /*---------职称下拉框选择回显---------*/
    getLabelById(id) {
      const item = this.profttlIds.find(option => option.id === id);
      return item ? item.label : '';
    },

    /*---------职称删除---------*/
    removeItem(index) {
      this.selectedValues.splice(index, 1);
    },

    /*---------新增修改表单嵌套的表格双击高亮处理---------*/
    handleRowClick(row) {
      this.$refs.myTable.setCurrentRow(row);
      const table = this.$el.querySelector('.el-table__body');
      table.querySelectorAll('tr').forEach(tr => {
        tr.classList.remove('perm-highlight');
      });
      event.currentTarget.classList.add('perm-highlight');
      this.selectedRow = row;
    },

    /*---------项目价格下拉框获取数据---------*/
    async loadItemPriceOptions() {
      const res = await getChargingPrice();
      const idsInTable = this.tableData2.map(item => item.costid);
      console.log(idsInTable, 'idsInTableidsInTable')
      this.itemPriceOptions = res.data.map(item => ({
        id: item.id,
        label: item.costname,
        odcost: item.odcost,
        pycode: pinyin(item.costname, {pattern: 'first', toneType: 'none', separator: ''}).toLocaleUpperCase(),
      }));
    },

    /*---------新增挂号类别---------*/
    handleAddPriceData() {
      if (!this.addPriceForm.costid) {
        this.$message.warning('请选择项目')
        return
      }
      const isDuplicate = this.tableData2.some(item =>
          item.costid === this.addPriceForm.costid
      );

      if (isDuplicate) {
        this.$message.warning('该项目已存在，请勿重复添加');
        return;
      }
      const foundItem = this.itemPriceOptions.find(item => item.id === this.addPriceForm.costid);
      this.addPriceForm.odcost = foundItem.odcost;
      this.tableData2.push(this.addPriceForm)
      this.addPriceDialogVisible = false;
      this.addPriceForm = Object.assign({}, this.$options.data.call(this).addPriceForm)
    },

    /*---------修改对应费用(项目价格接口)---------*/
    handleEditPriceData() {
      if (!this.editPriceForm.costid) {
        this.$message.warning('请选择项目')
        return;
      }
      if (this.editPriceForm.num === null) {
        this.$message.warning('请输入数量')
        return;
      }
      const foundItem = this.itemPriceOptions.find(item => item.id === this.editPriceForm.costid);
      this.editPriceForm.odcost = foundItem.odcost;
      const index = this.tableData2.findIndex(
          item => item.costid === this.selectedRow.costid
      );
      this.$set(this.tableData2, index, {...this.editPriceForm});
      this.editPriceForm = Object.assign({}, this.$options.data.call(this).editPriceForm)
      this.$set(this.editPriceForm, 'num', 1);
      this.selectedRow = null;
      this.editPriceDialogVisible = false;
    },

    /*---------修改对应费用(项目价格)---------*/
    handlePriceEdit() {
      this.editPriceForm = Object.assign({}, this.$options.data.call(this).editPriceForm)
      this.editPriceForm = JSON.parse(JSON.stringify(this.selectedRow))
      this.editPriceDialogVisible = true;
    },

    /*---------删除对应费用(项目价格)---------*/
    handlePriceDelete() {
      this.tableData2 = this.tableData2.filter(
          item => item.costid !== this.selectedRow.costid
      );
      this.selectedRow = null;
    },


    /*---------新增下拉框聚焦处理---------*/
    addEvent(v, i) {
    },
    addEventChangge() {
    },

    editFormValue(item) {

    },

    /*---------新增挂号类别---------*/
    async addCategoryData() {
      await withLoading(this, '数据提交中...')(async () => {
        this.addForm.profttlIds = this.selectedValues;
        this.addForm.regJoinVOS = [...(this.addForm.regJoinVOS || []), ...this.tableData2];

        if (!this.addForm.profttlIds?.length || !this.addForm.regJoinVOS?.length) {
          this.$message.error(this.addForm.profttlIds?.length ? '请添加至少一项费用' : '请选择至少一个职称');
          return
        }

        this.addForm.regJoinVOS = this.addForm.regJoinVOS.filter(
            (item, index, arr) => arr.findIndex(v => v.id === item.id) === index
        );

        const res = await addCategoryData(this.addForm)
        if (res.code === 200) {
          this.addForm = Object.assign({}, this.$options.data.call(this).addForm)
          this.$refs.addFormRef.resetFields();
          this.addDialogVisible = false;
          this.selectedValues = [];
          this.tableData2 = [];
          await this.loadData();
        } else {
          this.$message.error(res.message)
        }
      });
    },

    async editCategoryData() {
      await withLoading(this, '数据提交中...')(async () => {
        this.editForm.profttlIds = this.selectedValues;
        this.editForm.regJoinVOS = [...this.tableData2];

        if (!this.editForm.profttlIds?.length || !this.editForm.regJoinVOS?.length) {
          return this.$message.error(this.editForm.profttlIds?.length ? '请添加至少一项费用' : '请选择至少一个职称');
        }
        if (this.editForm.startage > this.editForm.endage) return this.$message.error("年龄下限不能大于年龄上限")
        this.editForm.regJoinVOS = this.editForm.regJoinVOS.filter(
            (item, index, arr) => arr.findIndex(v => v.id === item.id) === index
        );
        const res = await editCategoryData(this.editForm)

        if (res.code === 200) {
          this.editForm = Object.assign({}, this.$options.data.call(this).editForm)
          this.editDialogVisible = false;
        } else {
          this.$message.error(res.message)
        }
      });
    },

    /*---------分页回显数据---------*/
    formatColumn(row, prop) {
      const value = row[prop];
      switch (prop) {
        case 'id':
          return this.mapToLabel(value, this.itemPriceOptions);
        case 'costid':
          return this.mapToLabel(value, this.itemPriceOptions);
        case 'registertype':
          return this.mapToLabel(value, this.TypeOption);
        case 'status':
          return this.mapToLabel(value, this.statusOptions);
        default:
          return value; // 默认原样显示
      }
    },

    /*---------分页回显数据---------*/
    mapToLabel(value, options) {
      if (value === undefined || value === null) return '';
      const found = options.find(item => item.id == value);
      return found ? found.label : value;
    },


    handleNodeClick(data) {
      this.loadData();
    },


    /*---------数据源---------*/
    async loadData() {
      let res = await docregistertype({
        pageNum: this.pageNum,
        pageSize: this.pageSize,
        name: this.searchValue === '' ? '' : this.searchValue,
        status: this.pageDataState == null ? null : this.pageDataState
      })
      if (res.code !== 200) {
        this.$message.error(res.message)
      } else {
        this.tableData = res.data.content
        this.pageNum = res.data.pageNum
        this.pageSize = res.data.pageSize
        this.totalSize = res.data.totalSize
        this.CodeNumber = res.data.content.length
      }
    },

    columnWidth(col, list) {
      let prop = col.prop, lab = col.lab;
      let width = 40; // 设定一个最小值
      let maxlenStr = ""; // 最长字符串
      for (let info of list) {
        if (maxlenStr < (info[prop] + "").length) maxlenStr = info[prop];
      }
      width = Math.max(width, len(lab), len(maxlenStr));
      // 表格自带的内边距(20px) 自调
      return width + 8; // 这里加了 12px
      function len(str) {
        // 实际分配长度可根据需要自行调整
        let length = 12;
        for (const char of str + "") {
          // 英文小写字符 8px
          if ("a" <= char && char <= "z") length += 8;
          // 英文大写字符 8px
          else if ("A" <= char && char <= "Z") length += 8;
          // 中文字符 28px
          else if (char >= "\u4e00" && char <= "\u9fa5") length += 12;
          // 其他 8px
          else length += 12;
        }
        return length;
      }
    },

    /*---------启用禁用挂号类别---------*/
    async handleStartOrDisabled(row) {
      const action = row.status === '1' ? '禁用' : '启用'
      this.$confirm(`请确认是否${action}【${row.designation}】`, "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      }).then(async () => {
        await withLoading(this, `${action}处理中...`)(async () => {
          // 直接修改状态并提交
          const rs = await getCategory({regTyped: row.id})
          this.editForm = {...row}
          this.editForm.status = row.status === '1' ? '0' : '1';
          this.editForm.profttlIds = rs.data.profttlVOS.map(item => item.id);
          this.editForm.regJoinVOS = rs.data.costnametableVOS;
          let res = await editCategoryData(this.editForm);
          if (res.code === 200) {
            await this.loadData()
          } else {
            this.$message.error(res.message);
            await this.loadData()
          }
        });
      }).catch(() => {
        this.loadData()
      });
    },

    /*---------关闭模态框清空数据处理---------*/
    handleClose(done) {
      this.dialogVisible = false;
      this.formdisabled = false;
      this.editDialogVisible = false;
      this.addDialogVisible = false;
      this.addPriceDialogVisible = false;
      this.editPriceDialogVisible = false;
      this.timeRange = [
        new Date(1970, 0, 1, 0, 0, 0),
        new Date(1970, 0, 1, 0, 0, 0),
      ];
      this.selectedValues = [];
      this.selectedRow = [];
      this.tableData2 = [];
      this.addForm = Object.assign({}, this.$options.data.call(this).addForm)
      this.editForm = Object.assign({}, this.$options.data.call(this).editForm)
      this.addPriceForm = Object.assign({}, this.$options.data.call(this).addPriceForm)
      this.$refs.addFormRef.resetFields();
      this.loadData();
    },

    async handledbRow(row, column, event) {
      if (row) {
        this.dynamicTitle = '查看'
        this.isLookData = true;
        this.editForm = row;
        this.editDialogVisible = true
        this.tableData2 = null;
        this.selectedValues = null;
        const res = await getCategory({regTyped: row.id})
        await this.handleSelectionChange();
        this.selectedValues = res.data.profttlVOS.map(item => item.id)
        this.tableData2 = res.data.costnametableVOS
        await this.loadItemPriceOptions();
        this.timeRange = [
          new Date(`1970-01-01T${res.data.starttime}`),
          new Date(`1970-01-01T${res.data.endtime}`)
        ];
        this.editForm = JSON.parse(JSON.stringify(res.data))
        this.editForm.status = parseInt(this.editForm.status)
        this.editForm.registertype = parseInt(this.editForm.registertype)
        this.editDialogVisible = true;
      } else {
        console.log('fail');
      }
    },

    /*---------按钮顺序处理---------*/
    handClick(i) {
      switch (i) {
        case 0:
          this.loadData();
          break;
        case 1:
          // 处理索引2的逻辑 => 新增
          this.watch = '新增';
          this.addDialogVisible = true;
          this.selectedRow = null;
          this.selectedValues = [];
          this.tableData2 = [];
          break;
      }
    },

    /*---------禁用启用数据查询---------*/
    handleCommand(command) {
      this.pageDataState = command === 'a' ? 1 : command === 'b' ? 0 : command === 'c' ? null : null;
      this.DropDownedName = command === 'a' ? '可用' : command === 'b' ? '禁用' : '全部';
      this.loadData();
    },


    /*---------分页设置--------*/
    handleSizeChange(val) {
      this.pageSize = val;
      this.pageNum = 1;
      this.loadData();
    },
    //当前条数改变触发
    handleCurrentChange(val) {
      console.log(`当前页: ${val}`);
      this.pageNum = val;
      this.loadData();
    },
    // 实时宽度
    updateWindowWidth() {
      this.windowWidth = window.innerWidth - 288;
    },

    getColumnWidth(label, prop, tableData) {
      const minWidth = 100;
      const padding = 30; // 增加边距缓冲
      const contentList = tableData.map(item => item?.[prop] ?? '');

      // 计算所有内容宽度（包括表头）
      const widths = [...contentList, label].map(text => {
        const str = String(text || '');
        return this.getTextWidth(str) + padding;
      });

      return Math.max(minWidth, ...widths);
    },

    // 精确计算文本宽度（使用Canvas）
    getTextWidth(text, fontSize = 14) {
      const canvas = document.createElement('canvas');
      const ctx = canvas.getContext('2d');
      ctx.font = `${fontSize}px Microsoft YaHei`;
      return ctx.measureText(text).width;
    },

    labelHead(h, {column, $index}) {
      let l = column.label.length;
      let f = 12;
      column.minWidth = f * (l + 5); //加上一个文字长度
      return h("div", {class: "table-head", style: {width: "100%"}}, [
        column.label,
      ]);
    },

    safeGetMappedValue(col, row, type) {

      const hiddenProps = new Set([
        'usedfrquId', 'sdoseCnt', 'prdCnt', 'prdDays', 'medcWayId', 'tcmCnt',
        'selfProe', 'skintstRslt', 'remark', 'remarks', 'rxDosCnt',
      ]);

      if (hiddenProps.has(col.prop)) {
        return ''; // 直接返回空字符串，不显示
      }
      // 1. 检查数据有效性
      const rawValue = row[col.prop];
      if (rawValue === null || rawValue === undefined) return ' ';

      // 2. 检查映射数组
      const mapArray = this[col.op];
      if (!col.op || !Array.isArray(mapArray)) return rawValue;

      // 3. 执行映射
      const matched = mapArray.find(item => item.id == rawValue);
      return matched?.label || rawValue;
    },
  }
}
</script>


<style lang="less" scoped>
.el-dialog {
  min-width: 400px; /* 最小宽度防止挤压 */

  .el-dialog__body {
    padding: 10px 15px !important; /* 减少内边距 */
  }

  @media (max-width: 768px) {
    width: 90% !important;
    min-width: unset;
  }

  /* 移动端超小屏幕 */
  @media (max-width: 480px) {
    width: 95% !important;
  }
}

/* 紧凑型表单容器 */
.compact-form {
  .el-form-item {
    margin-bottom: 6px !important; /* 减少表单项间距 */

    &__label {
      padding-bottom: 0 !important;
      line-height: 22px !important;
      height: 22px !important;
    }

    &__content {
      line-height: 22px !important;
    }
  }

  /* 紧凑行布局 */

  .el-row {
    margin-bottom: -5px !important; /* 抵消列间距 */

    .el-col {
      padding-bottom: 5px !important;
    }
  }

  /* 紧凑多选标签 */

  .multi-select-container {
    margin: 4px 0 8px !important;

    .select-row {
      margin-bottom: 2px !important;

      .selected-tags {
        margin-top: 2px !important;

        .el-tag {
          margin: 0 4px 2px 0 !important;
        }
      }
    }
  }

  /* 紧凑表格头部 */

  .table-header {
    margin: 4px 0 6px !important;

    .transparent-btn {
      padding: 3px 5px !important;
    }
  }

  /* 紧凑表格 */

  .el-table {
    margin-top: 5px !important;

    th, td {
      padding: 3px 0 !important;
    }

    .cell {
      line-height: 20px !important;
    }
  }

  /* 紧凑时间选择器 */

  .compact-time-pickers {
    .el-date-editor {
      .el-range-input {
        height: 22px !important;
      }

      .el-range-separator {
        line-height: 22px !important;
      }
    }
  }
}

/* 对话框底部按钮 */
.dialog-footer {
  padding: 8px 15px !important;

  .el-button {
    padding: 5px 10px !important;
    margin-left: 8px !important;
  }
}

.multi-select-container {
  padding: 20px;
}

.select-row {
  display: flex;
  align-items: center;
  margin-bottom: 10px;
}

.select-label {
  font-size: 14px;
  color: #606266;
  margin-right: 10px;
  white-space: nowrap;
  flex-shrink: 0;
}

.select-with-tags {
  display: flex;
  align-items: center;
  flex-wrap: wrap;
  gap: 8px;
  flex: 1;
}

.selected-tags {
  display: flex;
  flex-wrap: wrap;
  gap: 6px;
  margin-left: 10px;
}

.id-array {
  margin-top: 10px;
  color: #666;
  font-size: 14px;
}

.el-select {
  width: 150px;
}

.el-tag {
  margin-right: 6px;
}

.el-table :deep(.perm-highlight) {
  background-color: #000 !important;
}

.el-table :deep(.perm-highlight) > td {
  background-color: transparent !important;
}

/* 覆盖Element默认高亮色 */
.el-table :deep(.current-row) {
  background-color: #000 !important;
}


.transparent-btn-group {
  background-color: transparent !important;
  border: none !important;
  box-shadow: none !important;
}

.transparent-btn {
  background-color: transparent !important;
  border: none !important;
  color: white !important; /* 图标设为白色 */
  padding: 6px 8px !important;
  font-size: 14px !important;
}

.transparent-btn:hover {
  background-color: rgba(255, 255, 255, 0.2) !important; /* 悬停效果 */
}

.transparent-btn:active {
  transform: scale(0.95);
}

.transparent-btn-group {
  background-color: transparent !important;
  border: none !important;
  box-shadow: none !important;
}

.table-header {
  background-color: #39648f; /* 深蓝色，与图片一致 */
  color: white;
  padding: 3px 4px;
  display: flex;
  justify-content: space-between;
  align-items: center;
  border-radius: 5px 4px 0 0;

}

// 穿透
/deep/ .el-input.is-disabled .el-input__inner {
  color: #87898f;
}

/deep/ .el-textarea.is-disabled .el-textarea__inner {
  color: #87898f;
}

/deep/ .el-icon-arrow-left:before {
  content: "\e67d";
  font-size: 18px;
}

/deep/ .el-dialog__title {
  font-size: 12px;
  color: #fff;
}

/deep/ .el-dialog__headerbtn {
  top: 12px;
}

/deep/ .el-dialog__headerbtn .el-dialog__close {
  color: #fff;
}

/deep/ .el-dialog__headerbtn .el-dialog__close:hover {
  color: #00007f;
}

/deep/ .el-dialog__header {
  background-color: #39648f;
  padding: 8px;
}

/deep/ .el-dialog__body {
  padding: 0 20px 0 20px;
  border: 1px solid #efefef;
  padding: 8px;
}

/deep/ .el-dropdown-menu__item {
  font-size: 12px;
}

/deep/ .el-descriptions {
  font-size: 12px !important;
}

/deep/ .el-descriptions-item__container {
  display: flex !important;
  // align-items: center !important;
  padding-top: 12px !important;
}

/deep/ .el-descriptions-item__label:not(.is-bordered-label) {
  padding-left: 0;
  width: 66px;
  display: flex;
  justify-content: right;
}

/deep/ .el-color-picker__icon, .el-input, .el-textarea {
  width: 100%;
}

// content
.MedicenCata {
  height: 100%;
  width: 100%;
  // header
  .header {
    display: flex;
    flex-direction: row;
    align-items: center;
    height: 40px;
    background-color: #efefef;
    padding: 4px;

    // justify-content: space-evenly;
    // icon
    .header-icon {
      display: flex;
      align-items: center;
    }

  }

  // main
  .main {
    width: 100%;
    display: flex;
    justify-content: space-between;
    // height: 473px; /* 设置父容器的高度 */
    // overflow-y: auto; /* 当内容超出容器高度时显示垂直滚动条 */
    // left

    // right
    .main-right {
      flex: 1;
      width: 100%;
      height: 100%;
      // alert
      .addmessagesBox {
        .tabs {
          /deep/ .el-select > .el-input {
            width: 172px;
          }

          /deep/ .el-date-editor.el-input, .el-date-editor.el-input__inner {
            width: 172px;
          }

          /deep/ .el-form-item__content {
            display: flex;

            span {
              font-size: 12px;
            }
          }

          .oneLine {
            width: 524px;
            // background-color: indianred;
          }
        }

        /deep/ .el-dialog__title {
          font-size: 12px;
        }

        /deep/ .el-table {
          font-size: 12px;
        }

      }

      // icon
      .main-icon {
        display: flex;
        align-items: center;
        padding: 12px;
        line-height: 40px;

        .main-icon-a {
          // width: 240px;
          // background-color: #00557f;
        }

        .main-icon-b {
          margin-left: 28px;

          /deep/ .el-dropdown {
            font-size: 12px;
            cursor: pointer;
          }

          /deep/ .el-dropdown:hover {
            font-weight: bold;
            color: #66b1ff;
          }

          /deep/ .el-icon--right {
            // background-color: #66b1ff;
          }

          /deep/ .el-popper[x-placement^=bottom] {
            margin-top: 0;
          }
        }

        // c
        .main-icon-c {
          display: flex;
          margin-left: 28px;

          /deep/ [data-v-2bacc09b] .el-color-picker__icon, .el-input[data-v-2bacc09b], .el-textarea[data-v-2bacc09b] {
            width: 80%;
          }
        }
      }

      // table
      /deep/ .el-table .cell {
        font-size: 12px;
        text-align: center;
      }

      /deep/ .el-table td.el-table__cell div :first-child {
        text-align: center;
      }

      /deep/ .el-table td.el-table__cell div {
        text-align: center;
        overflow: hidden;
        white-space: normal;
        word-break: break-all;
      }

      .table {

      }
    }
  }

  // feet
  .feet {
    .addmessagesBox {
      .aform {
        padding: 12px;
        margin-top: 12px;
        border: 1px solid #e7e7e7;
      }

      .bform {
        padding: 12px;
        margin-top: 12px;
        border: 1px solid #e7e7e7;
      }
    }

    // alert
    .messagesBox {
      .tabs {

        /deep/ .el-form-item__content {
          display: flex;

          span {
            font-size: 12px;
          }
        }

        .oneLine {
          width: 524px;
          // background-color: indianred;
        }
      }

      /deep/ .el-dialog__title {
        font-size: 12px;
      }

      /deep/ .el-table {
        font-size: 12px;
      }

    }
  }

}
</style>